package com.huazai.yangge.completable.future;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author 华仔
 * @date 2024/2/21
 */
public class CompletableFutureMallDemo {
    // 功能--->性能
    // 需求说明
    // 同一款产品，同时搜索出不同款产品在各大电商平台的价格
    // 同一款产品，同时搜索出本产品在同一个电商平台下，各个入住卖家的售价是多少
    static List<NetMall> list =
            Arrays.asList(new NetMall("jd"), new NetMall("taobao"), new NetMall("dangdang"));

    public static List<String> getPrice(List<NetMall> list, String productName) {
       return list.stream()
                .map(netMall ->
                        String.format(productName + "in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName)))
                .collect(Collectors.toList());

    }

    public static List<String> compoletableFuturePrice(List<NetMall> list, String productName) {
       return list.stream()
                .map(netMall ->
                        CompletableFuture.supplyAsync(() ->
                                String.format(productName + "in %s price is %.2f",
                                        netMall.getNetMallName(),
                                        netMall.calcPrice(productName))
                        )).collect(Collectors.toList()).stream().map(s -> s.join()).collect(Collectors.toList());


    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        final List<String> mysql = getPrice(list, "mysql");
        for (String s : mysql) {
            System.out.println("s = " + s);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("costTime = " + (endTime - startTime) + "毫秒");

        //===================
        long startTime1 = System.currentTimeMillis();
        final List<String> mysql1 = compoletableFuturePrice(list, "mysql");
        for (String s : mysql1) {
            System.out.println("s = " + s);
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("costTime = " + (endTime1 - startTime1) + "毫秒");
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class NetMall {
    private String netMallName;

    public double calcPrice(String productName) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }

}




